package serversidepkg;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import backendpkg.DataSource;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

/**
 * Servlet implementation class StartChat
 */
public class StartConversation extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public StartConversation() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		try { 
			response.setHeader("Cache-Control","no-cache"); //Forces caches to obtain a new copy of the page from the origin server
			response.setHeader("Cache-Control","no-store"); //Directs caches not to store the page under any circumstance
			response.setDateHeader("Expires", 0); //Causes the proxy cache to see the page as "stale"
			response.setHeader("Pragma","no-cache"); //HTTP 1.0 backward compatibility
			
			//Get username from session
			HttpSession session = request.getSession();			
            String user = (String) session.getAttribute("username");

            if (user == null) {
               request.setAttribute("Error", "Session has ended.  Please login.");
               RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
               rd.forward(request, response);
            }else{			
	            String sender = user;
				//Get Parameters from request
	            String receiver = request.getParameter("receiver");
	            String tabnum = request.getParameter("tabnum");
	            String accepted = "NULL";
	            
	            //Get connection to database
	            DataSource datasource = new DataSource();
	            Connection conn = datasource.getConnection();
	            PreparedStatement statement;
	            
	            //Check if chat already exists
	        	String chat_exist = "SELECT * FROM Chat WHERE (user1=? AND user2=?) OR (user1=? AND user2=?)";
	        	statement = (PreparedStatement) conn.prepareStatement(chat_exist);
	        	statement.setString(1, sender);
	        	statement.setString(2, receiver);
	        	statement.setString(3, receiver);
	        	statement.setString(4, sender);
	        	
	        	ResultSet result = statement.executeQuery();
	        	
	        	if(result.next())
	        		accepted="false"; //if already exist set accepted to false in incoming
	            
	            
	        	String sql = "INSERT INTO Incoming (receiver, sender, sender_tab_num, accepted, newchatID)"
	                    +" VALUES (?,?,?,?,NULL)";
	            //DB insert
	            statement = (PreparedStatement) conn.prepareStatement(sql);
	            statement.setString(1, receiver);
	            statement.setString(2, sender);
	            if(tabnum != null)
	            	statement.setInt(3, Integer.parseInt(tabnum));
	            statement.setString(4, accepted);
	            statement.executeUpdate();
	               
	            conn.close();
            }
        } catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
            
        }
	}

}